#!/usr/bin/env python
#-*- coding: utf-8 -*-"
######################################################################
# Copyright (c) 2010 Eugene Vorobkalo.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v2.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
#
# Contributors:
#     Eugene Vorobkalo - initial API and implementation
#     Andrey Fedorov
######################################################################


from xmlrpclib import Binary
import os
from os import lstat

from log import Log
from cfg import PROXY_MODULE, DEBUG_LEVEL, APK_FILENAME, GetApkVersion, WORK_DIR, Guid2Id
#WORK_DIR = os.path.dirname(__file__).replace('\\','/') + '/'

# Модуль посредник для обменна данными
proxy = __import__('proxy_mod.' + PROXY_MODULE, fromlist=['proxy_mod'])
try:
    proxy.init(Log)
except:
    pass

_apk_size       = 0
_apk_time       = 0
_apk_version    = 0

class DroidPresInstance:
    ERR_AgentID     = u'Agent ID is not set'
    ERR_DocEmpty    = u'A document obtained by not fully'
    #DeviceGUID = None

    def GetZipData(self, DeviceGUID):
        try:
            AgentID = Guid2Id(DeviceGUID)
            if AgentID:
                ZIP_FILENAME = WORK_DIR + 'db/CSV_Data/Agent%d.zip'%(AgentID)
                Found = 0
                if os.path.isfile(ZIP_FILENAME):
                    Found = 1
                if Found == 1:
                    zip_file_state = lstat(ZIP_FILENAME)
                    zip_file_size = zip_file_state.st_size
                    if DEBUG_LEVEL > 0:
                        Log("GetZipData:\t AgentID=%d Sending DataSize=%d" % (AgentID, zip_file_size))
                    with open(ZIP_FILENAME, "rb") as handle:
                        return Binary(handle.read())
                else:
                    if DEBUG_LEVEL > 1:
                        Log("GetZipData:\t Zip file for AgentID=%d not found"%(AgentID))
                    return Binary('0')
        except Exception as e:
            Log(e, True)
            raise

    def GetUpdateApp(self, version):
        global _apk_size, _apk_time, _apk_version
        try:
            apk_state = lstat(APK_FILENAME)
            if apk_state.st_ctime <> _apk_time or apk_state.st_size <> _apk_size:
                _apk_time = apk_state.st_ctime
                _apk_size = apk_state.st_size
                _apk_version = GetApkVersion()

            if DEBUG_LEVEL > 0:
                Log("GetUpdateApp:\t Client version=%d, Current version: %d" % (version, _apk_version))
            if version < _apk_version:
                if DEBUG_LEVEL > 1:
                    Log("GetUpdateApp:\tSend ubdate APK v: %d" % _apk_version)
                with open(APK_FILENAME, "rb") as handle:
                    return Binary(handle.read())
            else:
                if DEBUG_LEVEL > 1:
                    Log("GetUpdateApp:\tUpdate does not require")
                return Binary('0')
        except Exception as e:
            Log(e, True)
            raise

    def SetDocs(self, DeviceGUID, DocsData):
        try:
            if not DocsData:
                raise Exception(self.ERR_DocEmpty)

            if DEBUG_LEVEL > 0:
                Log("SetDocs:\t DeviceGUID=%s DocsData"%DeviceGUID)
            AgentID = Guid2Id(DeviceGUID)
            if not AgentID:
                raise Exception(self.ERR_AgentID)
            return proxy.SetDocs(AgentID, DocsData)

        except AttributeError as e:
            Log(e, True)
            return False
        except Exception as e:
            Log(e, True)
            raise

    def SetLocation(self, DeviceGUID, location):
        try:
            AgentID = Guid2Id(DeviceGUID)
            if not AgentID:
                raise Exception(self.ERR_AgentID)
            if DEBUG_LEVEL > 0:
                Log("SetLocation:\t AgentID=%s, Location count=%d" % (AgentID, len(location)))
            return proxy.SetLocation(AgentID, location)
        except AttributeError as e:
            Log(e, True)
            return False
        except Exception as e:
            Log(e, True)
            raise
